package com.songlanyun.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public final class DateUtil {
    private DateUtil() {
    }

    /**
     * 获取当前时间戳(秒级,10位数字)
     *
     * @return 时间戳
     */
    public static String getTimeStampSecond() {
        Instant timestamp = Instant.now();

        return String.valueOf(timestamp.toEpochMilli()).substring(0, 10);
    }

    public static Date parseDate(String dateTimeStr, String pattern) {
        Date date = null;
        SimpleDateFormat sf = new SimpleDateFormat(pattern);
        try {
            date = sf.parse(dateTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String formatData(Date date, String pattern) {
        return new SimpleDateFormat(pattern).format(date);
    }

    //"yyyy-MM-dd HH:mm:ss"

    /**
     * @param pattern 时间格式
     * @return 时间字符串
     */
    public static String getNowTime(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    /**
     * 获取每月的第一天 Local 2020 - 09 -01
     *
     * @param time
     * @return
     */
    public static LocalDate getLocalMonthBegin(String time) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parse = LocalDate.parse(time, fmt);

        LocalDate stdate = parse.with(TemporalAdjusters.firstDayOfMonth());// LocalDate.parse(stdStr, fmt);
        return stdate;
    }

    /**
     * 获取每月的最后一天 Local 2020 - 09 -30
     *
     * @param time
     * @return
     */
    public static LocalDate getLocalMonthEnd(String time) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parse = LocalDate.parse(time, fmt);

        LocalDate etDate = parse.with(TemporalAdjusters.lastDayOfMonth());
        return etDate;
    }
}
